// index.js

var app = getApp();
Page({
  data: {
    shops: '',
    goodsList: '',
    globalData: '',
    choiceShop: {
      visible: false,
      title: '请选择店铺',
      items: [{
          label: '兴业园店',
        },
        {
          label: '大修厂店',
        }
      ]
    }
  },

  onLoad() {
    this.setData({
      shops: app.data.shops
    })

    if(this.data.shops.index === 0){
      wx.navigateTo({
        url: '/pages/choice-shop/index',
      })
    }

    app.data.setGetAllGoodsDoneCallback = (()=>{
      this.setData({
        goodsList: app.data.globalData.allGoodsList,
        globalData: app.data.globalData,
      })
      console.log('拉取到了商品列表，回调中：', this.data.goodsList)
      wx.hideToast();
    }).bind(this);

    // 2. get all goods list
    app.getAllGoodsList();
  },
  
  onShow() {
    this.getTabBar().init();
    this.setData({
      'shops.index': this.data.shops.index
    })

    if(app.data.globalData.allGoodsList){
      this.setData({
        goodsList: app.data.globalData.allGoodsList,
        globalData: app.data.globalData,
      })
    }else if(0 !== this.data.shops.index){
      wx.showToast({
        title: '加载中...',
        icon: 'loading',
        mask: true,
        duration: 1500
      })
    }
  },

  onReady(){
  },

  onPullDownRefresh() {
    // console.log('onPullDownRefresh')
    // 1. 重新加载一次商品列表
    app.getAllGoodsList();

    // 2. 重新加载一次商品列表
    wx.reLaunch({
      url: '/pages/index/index',
      complete(){
        wx.stopPullDownRefresh();
      },
    })
  },

  goodListClickHandle(e) {
    // const { index } = e.detail;
    // const { spuId } = this.data.goodsList[index];
    // console.log(e.detail)
    // console.log(spuId)
  },

  goodListAddCartHandle() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '点击加入购物车',
    });
  },
  toPay(){
    if(0 === app.data.shops.index){
      wx.navigateTo({
        url: '/pages/choice-shop/index',
      })
    }
    wx.switchTab({
      url: '/pages/order/order',
    })
  },
  gotoShopChoice(){
    wx.navigateTo({
      url: '/pages/choice-shop/index',
    })
  }
})
